import utils from '../utils'
import {DataTable} from '../data'
// utility functions for layers

// Divide a collection of features with mixed types into layers of a single type
// (Used for importing TopoJSON and GeoJSON features)
function divideFeaturesByType(shapes, properties, types) {
  const typeSet = utils.uniq(types)
  const layers = typeSet.map((geoType) => {
    const p = []
    const s = []
    let dataNulls = 0
    let rec = null
    for (let i=0, n=shapes.length; i<n; i++) {
      if (types[i] != geoType) continue
      if (geoType) s.push(shapes[i])
      rec = properties[i]
      p.push(rec)
      if (!rec) dataNulls++
    }
    return {
      geometry_type: geoType,
      shapes: s,
      data: dataNulls < s.length ? new DataTable(p) : null
    }
  })
  return layers
}
function copyLayerShapes(lyr) {
  const copy = utils.extend({}, lyr)
  if (lyr.shapes) {
    copy.shapes = utils.cloneShapes(lyr.shapes)
  }
  return copy
}
function getLayerBounds(lyr, arcs) {
  let bounds = null
  if (lyr.geometry_type == 'point') {
    bounds = utils.getPointBounds(lyr.shapes)
  } else if (lyr.geometry_type == 'polygon' || lyr.geometry_type == 'polyline') {
    bounds = getPathBounds(lyr.shapes, arcs)
  } else {
    // just return null if layer has no bounds
    // error("Layer is missing a valid geometry type");
  }
  return bounds
}
function getPathBounds(shapes, arcs) {
  const bounds = new Bounds()
  utils.forEachArcId(shapes, (id) => {
    arcs.mergeArcBounds(id, bounds)
  })
  return bounds
}
export default {
  divideFeaturesByType,
  copyLayerShapes,
  getLayerBounds,
}